<?php
/**
 * Created by PhpStorm.
 * User: 69548
 * Date: 2018/7/23
 * Time: 17:50
 */

namespace app\api\controller;

use app\admin\model\GeoHash;
use app\api\model\HotelSpu;
use think\Cache;
use think\Exception;
use think\Request;
use think\db;
use app\common\controller\Api;
use app\api\model\Standard as SD;
use app\api\model\Poi;
use app\api\controller\Esapi as EsapiController;
use think\Cookie;
use think\db\Expression;
use think\exception\DbException;
use app\wap\controller\Notify as WapNotify;


class Standard extends Api{
    public function __construct()
    {
        parent::__construct();
    }
    //鉴权
    public function checAuth($post)
    {
        //验证鉴权
        $match_arr = array(
            "secret",
            "secret_code"
        );
        $match_res = $this->match_post($match_arr,$post);
        if($match_res['code']==200){
            if(!$this->ApiValidate($post['secret_code'],$post['secret'])){
                //鉴权失败
                return false;
            }else{
                return true;
            }
        }

        return $match_res;
    }
    //获取标品列表
    public function getStandardList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $from = $post['from']??'toC';
        $model = new SD();
        list($total,$list) = $model->getList($post,$page,$offset,$from);
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //获取标品详情
    public function getStandardInfo()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['id']??0;
        $model = new SD();

        $detail = $model->getDetail($standard_id,'orderSystem');
        if(empty($detail)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$detail]);
        }
    }

    //获取所有套餐价格
    public function getStandardSpecPrice()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $date = $post['date']??"";
        $standard_id = $post['id']??0;
        $where['s.id'] = $standard_id;
        $info = db("standard s")
            ->field("s.*,st.costCurrency,st.trip_id")
            ->join("standardtrip st",'st.sid=s.id','left')
            ->where($where)
            ->find();
        if(empty($info)){
            return json_encode(['code'=>-1,'msg'=>'标品信息不存在']);
        }
        $model = new SD();
        $priceList = $model->getGoodsSpecPriceByDate($info,$date);
        if(empty($priceList)){
            return json_encode(['code'=>-1,'msg'=>'标品套餐暂未配置']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$priceList]);
        }
    }

    /**
     * 获取酒店房价列表
     */
    public function getStandardRoomPrice()
    {
        $model = new SD();
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $standard_id = $post['id']??0;
        $list = $model->getRoomPrice($standard_id);
        return json_encode(['status'=>200,'msg'=>'success','data'=>$list]);exit;
    }

    //获取所有套餐日历
    public function getStandardSpecTimeList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['id']??0;
        $info = db("standard")->find($standard_id);
        if(empty($info)){
            return json_encode(['code'=>400,'msg'=>'标品数据不存在']);
        }else{
            if(empty($info['goods_id'])){
                return json_encode(['code'=>400,'msg'=>'标品暂未关联商品']);
            }
            $model = new SD();
            $list = $model->getStandardSpecTimeList($info['goods_id'],$standard_id);
            if(empty($list)){
                return json_encode(['code'=>400,'msg'=>'标品暂未设置套餐日历']);
            }else{
                return json_encode(['code'=>200,'msg'=>'success','data'=>['timelist'=>$list]]);
            }
        }
    }

    //获取toB系统标品列表
    public function getStandardListToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $page = $post['page']??1;
        $offset = $post['offset']??20;
        $model = new SD();
        list($total,$list) = $model->getList($post,$page,$offset,'toB');
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //获取toB系统标品详情
    public function getStandardInfoToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['id']??0;
        $model = new SD();

        $detail = $model->getDetail($standard_id,'toB');
        if(empty($detail)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$detail]);
        }
    }

    //获取标签分类列表
    public function getStandardTagsTypeListToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $list = db("tag_type")->select();
        if(empty($list)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
        }
    }

    //获取toB系统标签列表
    public function getStandardTagsListToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $tags_type = $post['tagsTypeId']??5;
        $where['tag_status'] = 1;
        $where['tag_type'] = ['in',$tags_type];

        $list = db("tag")->field("tag_id,tag_name,icon")->where($where)->select();
        if(empty($list)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
        }
    }

    //获取城市列表
    public function getStandardCityList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $topCate = $post['topCate']??0;
        //$list = Cache::get("citylist_toB");
        //获取所有城市列表
        $list = $this->getAllCityList($topCate);
        if(!empty($list)){
            return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
        }

        //$list = $this->refreshCityList();

        if(empty($list)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
        }
    }

    //刷新城市列表
    public function refreshCityList()
    {
        $where['groupid'] = 0 ;
        $where['deleted'] = 0 ;
        $list= db('city')->field("id,name")->where($where)->select();
        if (!empty($list)){
            //获取行程中的出发城市
            $standard_where['s.status'] = 1;//启用的标品
            $standard_where['s.is_deleted'] = 0;//未删除的标品
            $standard_where['s.show_toB'] = 1;//用于toB的标品
            $standard_where['st.startCityId'] = ['neq',0];//起点城市不为空
            $cityList = db("standard s")
                ->field("startCityId")
                ->join("standardtrip st","s.id=st.sid",'left')
                ->where($standard_where)
                ->select();
            if(empty($cityList)){
                return [];
            }
            $city_where['id'] = ['in',array_column($cityList,"startCityId")];
            foreach ($list as $key=>$value){
                $list[$key]['children'] = [];
                $city_where['groupid'] = $value['id'];
                $city_where['show'] = 1;
                $city_where['deleted'] = 0;
                $city_children = db('city')
                    ->where($city_where)
                    ->field('name,eng_name,id as city_id,categorytagids')
                    ->order("sort_weight desc")
                    ->select();
                if(!empty($city_children)){
                    $tagIds = [];
                    $otherCity = [];
                    foreach ($city_children as $child_k=>$child_v){
                        if(!empty($child_v['categorytagids'])){
                           $tagIds = array_filter(array_merge($tagIds,explode(",",$child_v['categorytagids'])));
                        }else{
                            $otherCity[] = $child_v;
                        }
                    }
                    if(!empty($tagIds)){
                        $tagNames = db("tag")->field("tag_id,tag_name")->where(['tag_id'=>['in',$tagIds]])->select();
                        foreach ($tagNames as $tag_k=>$tag_v){
                            $tagNames[$tag_k]['children'] = [];
                            foreach ($city_children as $child_k=>$child_v){
                                if(!empty($child_v['categorytagids'])){
                                    $cateIds = explode(",",$child_v['categorytagids']);
                                    if(in_array($tag_v['tag_id'],$cateIds)){
                                        $tagNames[$tag_k]['children'][] = $child_v;
                                        unset($city_children[$child_k]);
                                    }
                                }
                            }
                        }
                        if(!empty($city_children)){
                            $tagNames[] = [
                                'tag_id'=>0,
                                'tag_name'=>'其他城市',
                                'children'=>array_values($city_children)
                            ];
                        }
                    }else{
                        $tagNames = [[
                            'tag_id'=>0,
                            'tag_name'=>'其他城市',
                            'children'=>array_values($otherCity)
                        ]];
                    }
                    $list[$key]['children'] = $tagNames;
                }
            }
        }
        //缓存数据
        //每日凌晨失效
        $expire_time = date("Y-m-d H:i",strtotime("+1 day"));
        Cache::tag("toB")->set("citylist_toB",$list,new \DateTime($expire_time));
        return $list;
    }

    //获取toB和商品列表
    public function getGoodsListToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $page = $post['page']??1;
        $offset = $post['offset']??10;
        $from = $post['from']??'toC';
        $model = new SD();
        list($total,$list) = $model->getGoodsList($post,$page,$offset,$from);
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);

    }

    //获取toB和商品详情
    public function getGoodsInfoToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;
        $model = new SD();
        $details = $model->getGoodsInfo($standard_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }
    //获取商品套餐列表
    public function getGoodsSpecsToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;
        $model = new SD();
        $details = $model->getGoodsSpec($standard_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }

    //获取商品套餐详情
    public function getGoodsSpecsInfoToB()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;
        $time = $post['time']??0;
        $model = new SD();
        $details = $model->getGoodsSpecInfo($standard_id,$time);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }
    //获取所有的城市列表
    public function getAllCityList($topCate)
    {
        $where['groupid'] = 0 ;
        $where['deleted'] = 0 ;
        $list= db('city')->field("id,name")->where($where)->select();
        if (!empty($list)){
            foreach ($list as $key=>$value){
                $list[$key]['children'] = [];
                $city_where['groupid'] = $value['id'];
                $city_where['show'] = 1;
                $city_where['deleted'] = 0;
                $city_children = db('city')
                    ->where($city_where)
                    ->field('name,eng_name,id as city_id,categorytagids')
                    ->order("sort_weight desc")
                    ->select();
                if(!empty($city_children)){
                    //统计每个城市下面的数量
                    $city_children = $this->statisticalNumber($city_children,$topCate);
                    $tagIds = [];
                    $otherCity = [];
                    foreach ($city_children as $child_k=>$child_v){
                        if(!empty($child_v['categorytagids'])){
                            $tagIds = array_filter(array_merge($tagIds,explode(",",$child_v['categorytagids'])));
                        }else{
                            $otherCity[] = $child_v;
                        }
                    }
                    if(!empty($tagIds)){
                        $tagNames = db("tag")->field("tag_id,tag_name")->where(['tag_id'=>['in',$tagIds]])->select();
                        foreach ($tagNames as $tag_k=>$tag_v){
                            $tagNames[$tag_k]['children'] = [];
                            foreach ($city_children as $child_k=>$child_v){
                                if(!empty($child_v['categorytagids'])){
                                    $cateIds = explode(",",$child_v['categorytagids']);
                                    if(in_array($tag_v['tag_id'],$cateIds)){
                                        $tagNames[$tag_k]['children'][] = $child_v;
                                        unset($city_children[$child_k]);
                                    }
                                }
                            }
                        }
                        if(!empty($city_children)){
                            $tagNames[] = [
                                'tag_id'=>0,
                                'tag_name'=>'其他城市',
                                'children'=>array_values($city_children)
                            ];
                        }
                    }else{
                        $tagNames = [[
                            'tag_id'=>0,
                            'tag_name'=>'其他城市',
                            'children'=>array_values($otherCity)
                        ]];
                    }
                    $list[$key]['children'] = $tagNames;
                }else{
                    unset($list[$key]);
                }
            }
        }

        return $list;
    }

    //获取景点线路的标签分类
    public function getTourRouteTagList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        //默认是改版前 2是新版
        $topCate = $post['topCate']??1;
        $list = $this->getIndexTaglist(2,$topCate);
        if(empty($list)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
        }
    }
    //获取景点线路的标签分类[新版本 同级展示]
    public function getNewTourRouteTagList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $list = $this->getNewIndexTaglist();
        if(empty($list)){
            return json_encode(['code'=>404,'msg'=>'data is empty']);
        }else{
            return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
        }
    }
    /**
     * @param $list
     * @param int $topCate 1景点线路 2当地玩乐
     * @return mixed
     */
    public function statisticalNumber($list,$topCate=0)
    {
        if(!is_array($list) || empty($list)) return $list;
        foreach ($list as $key=>$value){
            $list[$key]['proKindNum'] = 0;
        }

        $topCate = (new SD())->getStandardTopCates();
        $topCateIds = array_column($topCate,'id');
        if(!in_array($topCate,$topCateIds)) return $list;
        $tags = [];
        foreach ($topCate as $value){
            if($topCate==$value['id']){
                $tagTypeIds = explode(',',$value['tagTypeIds']);
                $tags = db("tag")->where([
                    'tag_status'=>1,//未删除
                    'tob_show'=>1,//tob 展示
                    'tag_type'=>['in',$tagTypeIds],
                ])->column("tag_id");
                break;
            }
        }
        if(empty($tags)) return $list;
        $standard_id_arr = db("standardtags")->where(['tagid'=>['in',$tags]])->field("sid,count(sid) as count")->group("sid")->select();
        if(!empty($standard_id_arr)){
            $standard_id_arr = array_unique(array_column($standard_id_arr,"sid"));
            $where['s.id'] = ['in',$standard_id_arr];//用于搜索
        }else{
            return $list;
        }

        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品
        $standardList = db("standard s")->where($where)
            ->join("standardtrip st",'st.sid=s.id','left')
            ->field('s.id,s.type,s.startCity,st.startCityId')
            ->select();
        if(empty($standardList)) return $list;
        foreach ($standardList as $key=>$value){
            $cityId = $value['type']==1?$value['startCityId']:$value['startCity'];
            foreach ($list as $k=>$v){
                if($v['city_id']==$cityId){
                    $list[$k]['proKindNum']++;
                }
            }
        }

        return $list;
    }

    protected function getIndexTaglist($version=1,$topCate=1)
    {
        if($version==1){
            //改版前
            $list = [
                ['tag_id'=>'43,45','tag_name'=>'一日包车游'],
                ['tag_id'=>'43,46','tag_name'=>'一日参团游'],
                ['tag_id'=>'44,45','tag_name'=>'多日包车游'],
                ['tag_id'=>'44,46','tag_name'=>'多日参团游'],
//            ['tag_id'=>'57','tag_name'=>'英文服务'],
            ];
        }else{
            //分类标签
            $top_cates = db('tag')->where(['tag_type'=>5,'tag_status'=>1])->select();
            $second_cates = db('tag')->where(['tag_type'=>6,'tag_status'=>1])->select();
            $lineCate = [];
            foreach ($top_cates as $key=>$value){
                $cate = [];
                $cate['tag_id'] = $value['tag_id'];
                $cate['tag_name'] = $value['tag_name'];
                $cate['child'][] = ['tag_id'=>$value['tag_id'],'tag_name'=>'全部'];
                foreach ($second_cates as $k=>$v){
                    $cate['child'][] = [
                        'tag_id'=>$value['tag_id'].','.$v['tag_id'],
                        'tag_name'=>$v['tag_name']
                    ];
                }
                $lineCate[] = $cate;
            }

            if($topCate==1){
                $cate_tags = [
                    'name'=>'线路分类',
                    'child'=>$lineCate,
                ];
            }elseif($topCate==2){
                $cate_tags = db('tag')
                    ->field('tag_id,tag_name')
                    ->where(['tag_type'=>8])
                    ->select();
                $cate_tags = array_merge([['tag_id'=>'-1','tag_name'=>'全部']],$cate_tags);
                $cate_tags = [
                    'name'=>'玩乐分类',
                    'child'=>$cate_tags
                ];
            }
            //服务标签
            $server_tag_id = [57,58];//英文服务 中文服务
            //$exp = new \think\db\Expression('field(tag_id,57,56,59)');
            $server_tags = db('tag')
                ->field('tag_id,tag_name')
                ->where(['tag_id'=>['in',$server_tag_id]])
                //->order($exp)
                ->select();
            $server_tags = array_merge([['tag_id'=>'-1','tag_name'=>'全部']],$server_tags);
            //其他标签
            $other_tag_id = [56,59];//二次确认 即时确认
            //$exp = new \think\db\Expression('field(tag_id,57,56,59)');
            $other_tags = db('tag')
                ->field('tag_id,tag_name')
                ->where(['tag_id'=>['in',$other_tag_id]])
                //->order($exp)
                ->select();
            //加入全部
            //$other_tags = array_merge([['tag_id'=>'','tag_name'=>'全部']],$other_tags);
            //改版后
            $list = [
                $cate_tags,
                [
                    'name'=>'服务语言',
                    'child'=>$server_tags,
                ],
                [
                    'name'=>'其他',
                    'child'=>$other_tags,
                ]
            ];
        }
        return $list;
    }
    // 新版本的标签列表
    protected function getNewIndexTaglist()
    {
        //服务标签
        $server_tag_id = [57,58];//英文服务 中文服务
        //$exp = new \think\db\Expression('field(tag_id,57,56,59)');
        $server_tags = db('tag')
            ->field('tag_id,tag_name')
            ->where(['tag_id'=>['in',$server_tag_id]])
            //->order($exp)
            ->select();
        //其他标签
        $other_tag_id = [56,59];//二次确认 即时确认
        //$exp = new \think\db\Expression('field(tag_id,57,56,59)');
        $other_tags = db('tag')
            ->field('tag_id,tag_name')
            ->where(['tag_id'=>['in',$other_tag_id]])
            //->order($exp)
            ->select();
        //获取tob标签的类别
        $topCates = (new SD())->getStandardTopCates();
        $tagTypeIds = implode(',',array_column($topCates,'tagTypeIds'));
        $cate_tags = db("tag")->field('tag_id,tag_name')
            ->where(['tag_status'=>1])//未删除
            ->where(['tob_show'=>1])//tob 展示
            ->where(['tag_type'=>['in',$tagTypeIds]])
            ->order("tag_id asc")
            ->select();

        $list = [
            ['name'=>'产品分类','type'=>'checkbox','child'=>$cate_tags],
            ['name'=>'服务选择','type'=>'checkbox','child'=>[
                ['name'=>'服务语言','type'=>'radio','child'=>$server_tags],
                ['name'=>'确认时效','type'=>'radio','child'=>$other_tags]
            ]],
        ];
        return $list;
    }
    //通过城市获取周边的景点POI列表
    public function getPoiListByCityKbxId()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $cityid = $post['cityId']??'';//获取订单系统的城市id
        $city = db('city')
                ->field('id,name,lat,lng')
                ->where('kbx_id',$cityid)
                ->find();
        if(empty($cityid) || empty($city))
            return json_encode(['code'=>404,'msg'=>'未查询到城市']);

        $poiList = db('poi')->field('id,name,lat,lng')
                ->where(['groupid'=>$city['id'],'typeid'=>1,'deleted'=>0])
                ->select();
        if(empty($poiList))
            return json_encode(['code'=>404,'msg'=>'data is empty']);

        $intownList = [];
        $neighbourList = [];
        foreach ($poiList as $key=>$value){
            $value['distance'] = (new Poi())->getDistance($city['lat'],$city['lng'],$value['lat'],$value['lng']);
            if($value['distance'] <= 300000 && $value['distance'] > 200000){//周边的景点
                $value['distance'] = $value['distance']>1000?($value['distance']/1000).'km':$value['distance'].'m';
                $neighbourList[] = $value;
            }elseif($value['distance'] >= 0 && $value['distance'] <= 200000){//室内景点
                $value['distance'] = $value['distance']>1000?($value['distance']/1000).'km':$value['distance'].'m';
                $intownList[] = $value;
            }
        }

        return json_encode([
            'code'=>200,
            'msg'=>'success',
            'data'=>[
                'city'=>$city,
                'intownList'=>$intownList,
                'neighbourList'=>$neighbourList,
            ]
        ]);
    }
    //直接获取所有有城市的周边和市内景点
    public function getPoiListByCityList()
    {
        $city = db('city')
            ->field('id,name,lat,lng,kbx_id')
            ->where(['kbx_id'=>['neq',''],'deleted'=>0])
            ->select();
        if(!$city) return 'citylist empty';
        $city_id_arr = array_column($city,'id');
        if(!$city_id_arr) return 'citylist empty';

        $poiList = db('poi')->field('id,name,lat,lng,groupid,poi_sort,score')
            ->where(['groupid'=>['in',$city_id_arr],'typeid'=>1,'deleted'=>0])
            ->order('poi_sort desc,score desc')
            ->select();
        if(!$poiList) return 'poilist empty';
        $intownDistance = 100000;
        $neighbourDistance = 160000;
        foreach ($city as $key=>$value){
            $intownList = [];
            $neighbourList = [];
            foreach ($poiList as $k=>$v){
                if($v['groupid']==$value['id']){
                    $distance = (new Poi())->getDistance($value['lat'],$value['lng'],$v['lat'],$v['lng']);
                    $v['distance'] = $distance;
                    if($distance >= 0 && $distance <= $intownDistance){
                        $intownList[] = $v;
                    }elseif($distance < $neighbourDistance){
                        $neighbourList[] = $v;
                    }
                }
            }
            $city[$key]['intown'] = $city[$key]['neighbour'] = '';
            if(!empty($intownList)){
                //$distanceList = array_column($intownList,'distance');
                //array_multisort($distanceList,SORT_ASC,$intownList);
                $nameList = array_column($intownList,'name');
                $city[$key]['intown'] = implode(',',array_slice($nameList,0,10));
            }
            if(!empty($neighbourList)){
                //$distanceList = array_column($neighbourList,'distance');
                //array_multisort($distanceList,SORT_ASC,$neighbourList);
                $nameList = array_column($neighbourList,'name');
                $city[$key]['neighbour'] = implode(',',array_slice($nameList,0,10));
            }
            unset($city[$key]['id'],$city[$key]['lat'],$city[$key]['lng']);
        }

        return json_encode($city);
    }
    //标品ES搜索
    public function searchStandardListByES()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $esapi = new EsapiController();
        $page = $post['page']??1;
        $offset = $post['offset']??9;
        list($total,$list) = $esapi->esStandardSearch($post,$page,$offset);
        $data['total'] = $total;
        $data['totalPage'] = ceil($total/$offset);
        $data['curPage'] = (int)$page;
        $data['offset'] = (int)$offset;
        $data['list'] = $list;
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    public function getCityListByKeywordES()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $esapi = new EsapiController();
        $list = $esapi->esStandardCitySearch($post);
        return json_encode(['code'=>200,'msg'=>'success','data'=>$list]);
    }

    //订单系统采购商 获取上架的B端产品列表 用于新建采购商的商品模型
    public function getStandardListByBuyers($standard_id=0,$page=1,$offset=10)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        //增加筛选条件
        $keyword = !empty($post['keywords'])?trim($post['keywords']):'';
        $cityKbxIds = $post['cityIds']??[];
        $countryKbxIds = $post['countryIds']??[];
        $continentIds = $post['continentIds']??[];
        $tagIds = $post['tagIds']??[];
        // supplierId 特殊供应商也可以和agentSupplierId相同
        // agentSupplierId 分销商对应的供应商ID
        $supplier_id = $post['supplierId']??'';
        $agentSupplierId = $post['agentSupplierId']??"";//分销商对应的供应商ID
        //$authenticated = $post['authenticated']??true;//是否有资质 暂时不启用
        $except_ids = $post['exceptIds']??[];
        //关键词搜索
        if(!empty($keyword)) $where['s.id|s.name|g.goods_tcode'] = ['like','%'.$keyword.'%'];
        //出发城市
        if(!empty($cityKbxIds)){//城市级筛选
            $cityIds = db('city')->where(['kbx_id'=>['in',$cityKbxIds]])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }elseif(!empty($countryKbxIds)){//国家级筛选
            $countryIds = db('city')->where(['kbx_id'=>['in',$countryKbxIds]])->column('id');
            if(!empty($countryIds)){
                $cityIds = db('city')->where([
                    'groupid'=>['in',$countryIds],
                    'deleted'=>0,
                    'type'=>'CITY'
                ])->column('id');
                if(!empty($countryIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
            }
        }elseif(!empty($continentIds)){//洲级筛选
            $cityIds = db('city')->where([
                'continentid'=>['in',$continentIds],
                'deleted'=>0,
                'type'=>'CITY'
            ])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }
//        var_dump($cityIds);exit;
        //分类类型
        if(!empty($tagIds)){
            $standard_ids = (new SD())->getStandardIdsBytagIds($tagIds);
            $where['s.id'] = ['in',$standard_ids];
        }
        //排除已选产品
        //if(!empty($except_ids)) $where['s.id'] = ['not in',$except_ids];

        //采购商可采购所有通用的产品 有供应商的也可采购自营的产品
        //2021 03 13 补充说明
        // 1 supplierId存在 查看某家特定供应商产品
        // 2 agentSupplierId存在 查看自家的产品 + 允许分销的所有产品
        // 3 supplierId 和 agentSupplierId 都不存在 查看允许分销的所有产品
        if(!empty($supplier_id)){//查询特定供应商产品
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
            }
        }elseif(!empty($agentSupplierId)){
            $aegnt_supplier_admin_ids = $this->getSupplierAdminIds($agentSupplierId);
            if(!empty($aegnt_supplier_admin_ids)){
                $aegnt_supplier_admin_ids = implode(',',$aegnt_supplier_admin_ids);
                $where[] = new Expression('s.supplier_admin_id in ('.$aegnt_supplier_admin_ids.') or (s.supplier_admin_id not in ('.$aegnt_supplier_admin_ids.') and s.allow_everyone_quote=1)');
            }else{
            $where['s.allow_everyone_quote'] = 1;//其他供应商允许售卖的产品
            }
        }else{//无供应商 通用
            $where['s.allow_everyone_quote'] = 1;//其他供应商允许售卖的产品
        }

        $standardModel = new SD();
        $from = 'orderSystem';
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品
//        $topCate = (new SD())->getStandardTopCates();
//        $topCateIds = array_column($topCate,'id');
//        $where['s.topCate'] = ['in',$topCateIds];
        //是否允许其他人采购

        if(!empty($standard_id)) $where['s.id'] = $standard_id;//刷新单条数据
        $total = db("standard s")->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->where($where)->count();
        $list = db("standard s")
            ->where($where)
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->join("supplier_admin admin",'admin.supplier_admin_id=s.supplier_admin_id','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,
            g.goods_id,g.goods_name,g.orderType,is_recommend,trip_id,
            st.startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,
            days,endDays,subType,toursLineTitle,specialInfo,topCate,admin.company_id as supplierId')
            ->order("s.is_recommend desc,s.id desc")
            ->page($page,$offset)
            ->select();
//        var_dump($list);exit;
//        var_dump(db()->getLastSql());exit;
        foreach ($list as $key=>$value){
            $list[$key]['id'] = $value['standardId'];
            $list[$key]['goods_name'] = $value['standardName'];
            $list[$key]['standardTypeName'] = $standardModel->getTypeName($value['standardType']);
            $list[$key]['classificationTags'] = $standardModel->getStandardTags($value['standardId']);
            $list[$key]['subType'] = $standardModel->getSubType($value['subType']);
            $list[$key]['isSelected'] = !empty($except_ids)&&in_array($value['standardId'],$except_ids)?true:false;
            //获取关联的商品信息
            $list[$key]['goodsInfo'] = [];
            $list[$key]['showImg'] = "";
            if(!empty($value['goods_id'])){
                $list[$key]['goodsInfo'] = $standardModel->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                $image = $list[$key]['goodsInfo']['small_image']??[];
                $list[$key]['showImg'] = $standardModel->checkImgUrl($image[0]??"")??"";
//                $list[$key]['showImg'] = (new SD())->batchOssImgUrl($list[$key]['showImg']);
                $list[$key]['goodsprice'] = floatval($list[$key]['goodsInfo']['goodsprice'])??0;
                $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                unset($list[$key]['goodsInfo']['small_image']);
                $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
                $list[$key]['tags'] = !empty($list[$key]['goodsInfo']['tags'])?
                    array_merge($list[$key]['classificationTags'],$list[$key]['goodsInfo']['tags']):
                    $list[$key]['classificationTags'];
            }
        }   
        $result['pageInfo'] = [
            'totalNum'=>$total,
            'totalPage'=>ceil($total/$offset),
            'page'=>(int)$page,
            'offset'=>(int)$offset,
        ];
        $result['list'] = $list;
        //返回json 数据
        return $this->result('success',$result,200,'json');
    }
    //订单系统采购商 获取上架的B端产品分类列表
    public function getStandardCatesByBuyers()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $topCate = (new SD())->getStandardTopCates();
        $tagTypeIds = implode(',',array_column($topCate,'tagTypeIds'));
        $tagTypeIds = array_values(array_filter(explode(',',$tagTypeIds)));
        $cate_tags = db('tag')
            ->field('tag_id as tagId,tag_name as tagName,icon')
            ->where([
                'tag_type'=>['in',$tagTypeIds],
                'tag_status'=>1,
                'tob_show'=>1,
            ])
            ->select();
        //返回json 数据
        return json_encode(['code'=>200,'msg'=>'success','data'=>$cate_tags]);
    }
    //订单系统采购商 获取上架的B端产品列表 用于新建采购商的商品模型
    public function getAutoOnSaleStandardListByBuyers()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品

//        $topCate = (new SD())->getStandardTopCates();
//        $topCateIds = array_column($topCate,'id');
//        $where['s.topCate'] = ['in',$topCateIds];
        //特定供应商的产品
        $supplier_id = $post['supplierId']??'';
        if(!empty($supplier_id)){
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
                $list = db("standard s")->where($where)->column('s.id');
            }
        }
        if(empty($list)){
            unset($where['s.supplier_admin_id']);
            $where['auto_on_sale'] = 1;//用于小程序的模板标志
            $list = db("standard s")
                ->where($where)
                ->column('s.id');
        }
//        var_dump(db()->getLastSql());exit;
        $result['standardIds'] = $list;
        //返回json 数据
        return $this->result('success',$result,200,'json');
    }
    //订单系统采购商 获取选品后的产品列表
    public function getStandardListByStandardIds($page=1,$offset=10)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $ids = $post['ids']??[];
        if(empty($ids)) return json_encode(['code'=>400,'msg'=>'缺少选品IDs']);

        //增加筛选条件
        $keyword = !empty($post['keywords'])?trim($post['keywords']):'';
        $cityKbxIds = $post['cityIds']??[];
        $countryKbxIds = $post['countryIds']??[];
        $continentIds = $post['continentIds']??[];
        $tagIds = $post['tagIds']??[];
        $supplier_id = $post['supplierId']??'';
        $allData = $post['allData']??'';//默认只返回上架数据
        //关键词搜索
        if(!empty($keyword)) $where['s.id|s.name|g.goods_tcode'] = ['like','%'.$keyword.'%'];
        //出发城市
        if(!empty($cityKbxIds)){//城市级筛选
            $cityIds = db('city')->where(['kbx_id'=>['in',$cityKbxIds]])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }elseif(!empty($countryKbxIds)){//国家级筛选
            $countryIds = db('city')->where(['kbx_id'=>['in',$countryKbxIds]])->column('id');
            if(!empty($countryIds)){
                $cityIds = db('city')->where([
                    'groupid'=>['in',$countryIds],
                    'deleted'=>0,
                    'type'=>'CITY'
                ])->column('id');
                if(!empty($countryIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
            }
        }elseif(!empty($continentIds)){//洲级筛选
            $cityIds = db('city')->where([
                'continentid'=>['in',$continentIds],
                'deleted'=>0,
                'type'=>'CITY'
            ])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }
//        var_dump($cityIds);exit;
        //分类类型
        if(!empty($tagIds)){
            $standard_ids = (new SD())->getStandardIdsBytagIds($tagIds);
            $where['s.id'] = [['in',$ids],['in',$standard_ids]];
        }else{
            $where['s.id'] = ['in',$ids];//选品IDS
        }
        //特定供应商的产品
        if(!empty($supplier_id)){
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
            }
        }
        //按照参数的ids 进行排序
        $standardModel = new SD();
        $from = 'orderSystem';
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        if(empty($allData)) $where['s.show_toB'] = 1;//用于toB的标品
//        $topCate = (new SD())->getStandardTopCates();
//        $topCateIds = array_column($topCate,'id');
//        $where['s.topCate'] = ['in',$topCateIds];

        $total = $list = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->where($where)
            ->count();
        $list = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->join("supplier_admin admin",'admin.supplier_admin_id=s.supplier_admin_id','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,s.like_count as popular,
            g.goods_id,g.goods_name,g.orderType,is_recommend,trip_id,
            startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,
            days,endDays,subType,toursLineTitle,specialInfo,topCate,admin.company_id as supplierId')
            ->where($where)
            ->order(new Expression('field(s.id,'.implode(',',$ids).')'))
            ->page($page,$offset)
            ->select();
        foreach ($list as $key=>$value){
            $list[$key]['id'] = $value['standardId'];
            $list[$key]['goods_name'] = $value['standardName'];
            $list[$key]['standardTypeName'] = $standardModel->getTypeName($value['standardType']);
            $list[$key]['classificationTags'] = $standardModel->getStandardTags($value['standardId']);
            $list[$key]['subType'] = $standardModel->getSubType($value['subType']);

            //获取关联的商品信息
            $list[$key]['goodsInfo'] = [];
            $list[$key]['showImg'] = "";
            if(!empty($value['goods_id'])){
                $list[$key]['goodsInfo'] = $standardModel->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                $image = $list[$key]['goodsInfo']['small_image']??[];
                $list[$key]['showImg'] = $standardModel->checkImgUrl($image[0]??"")??"";
//                $list[$key]['showImg'] = (new SD())->batchOssImgUrl($list[$key]['showImg']);
                $list[$key]['goodsprice'] = floatval($list[$key]['goodsInfo']['goodsprice'])??0;
                $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                unset($list[$key]['goodsInfo']['small_image']);
                $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
                $list[$key]['tags'] = !empty($list[$key]['goodsInfo']['tags'])?
                    array_merge($list[$key]['classificationTags'],$list[$key]['goodsInfo']['tags']):
                    $list[$key]['classificationTags'];
            }
        }
        $result['pageInfo'] = [
            'totalNum'=>$total,
            'totalPage'=>ceil($total/$offset),
            'page'=>(int)$page,
            'offset'=>(int)$offset,
        ];
        $result['list'] = $list;
        //返回json 数据
        return $this->result('success',$result,200,'json');
    }
    //订单系统采购商 获取上架的B端产品详情
    public function getStandardInfoByBuyers()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);

        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;

        $model = new SD();
        $details = $model->getGoodsInfo($standard_id,'OrderSystem');
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                $details['recStandardList'] = $this->getRecommendStandardByStandardId($standard_id,'OrderSystem');
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }
    //订单系统采购商 获取上架的B端产品套餐
    public function getStandardPackageSpecByBuyers()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;
        $supplier_id = $post['supplierId']??'';
        //判断是否供应商采购商同账号
        $model = new SD();
        $details = $model->getGoodsPackageSpecByBuyer($standard_id,$supplier_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }
    //订单系统采购商 获取上架的B端产品日历价格
    public function getStandardSpecTimeByBuyers()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;
        $supplier_id = $post['supplierId']??'';
        $year = $post['year']??'';
        $month = $post['month']??'';
        $duration = $post['duration']??1;
        $model = new SD();
        $details = $model->getGoodsSpecByBuyer($standard_id,$year,$month,$duration,$supplier_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }
    //订单系统采购商 获取上架的B端产品套餐详情
    public function getStandardSpecPriceByBuyers()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;
        $supplier_id = $post['supplierId']??'';
        $time = $post['time']??0;
        $model = new SD();
        $details = $model->getGoodsSpecInfoByBuyer($standard_id,$time,$supplier_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }

    //获取供应商的所有账号集合
    public function getSupplierAdminIds($supplier_id)
    {
        //获取管理员ID
        return db('supplier_admin')->where([
            'company_id'=>$supplier_id,
            'is_use'=>1
        ])->column('supplier_admin_id');
    }
    //标品的状态检查
    public function checkStandardOnSaleStatus($standard_id)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $standard = db('standard')->find($standard_id);
        if(empty($standard_id) || empty($standard)) return json_encode(['code'=>400,'msg'=>'标品不存在']);
        $onSaleStatus = empty($standard['show_toB'])?false:true;
        return json_encode(['code'=>200,'msg'=>'success','data'=>[
            'onSaleStatus'=>$onSaleStatus
        ]]);
    }

    //获取洲级列表
    public function getContinentList()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $list = db('continent')->field('id as continentId,name as continentName,eng_name as continentEngName')->order('sort asc')->select();
        return $this->result('success',$list,200,'json');
    }

    //获取洲级类列表下的国家
    public function getCountryListByContinentIds($continentIds=[])
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        if(!empty($continentIds)){
            $where['c.continentid'] = ['in',$continentIds];
        }
        $where['c.groupid'] = 0;
        $where['c.type'] = 'COUNTRY';
        $where['c.deleted'] = 0;
        $where['c.kbx_id'] = ['neq',''];


        $list = db('city c')
            ->join('continent co','c.continentid=co.id','left')
            ->field('c.id,c.name,c.eng_name,c.kbx_id as countryKbxId,
            c.continentid as continentId,co.name as continentName,co.eng_name as continentEngName')
            ->where($where)->select();
        return $this->result('success',$list,200,'json');
    }

    //获取洲级类列表下的国家
    public function getCityListByCountryIds($countryIds=[])
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        if(!empty($countryIds)){
            $where['country.kbx_id'] = ['in',$countryIds];
        }
        $where['c.type'] = 'CITY';
        $where['c.deleted'] = 0;

        $list = db('city c')
            ->join('city country','country.id=c.groupid','left')
            ->join('continent co','co.id=c.continentid','left')
            ->field('c.id,c.name,c.eng_name,c.kbx_id as cityKbxId,
            c.continentid as continentid,co.name as continentName,co.eng_name as continentEngName,
            country.name as countryName,country.eng_name as countryEngName,country.kbx_id as countrykbxId')
            ->where($where)
            ->select();
        return $this->result('success',$list,200,'json');
    }

    //更新供应商的产品销量
    public function updateStandardSalesNoByStandardId()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $standardId = $post['standardId']??0;
        $salesVolume = $post['salesVolume']??0;
        $type = $post['type']??"inc";
        if(empty($standardId)) return json_encode(['code'=>400,'msg'=>'缺少产品ID']);
        if($salesVolume < 1) return json_encode(['code'=>400,'msg'=>'销量不能小于0']);
        if(!in_array($type,['inc','dec'])) return json_encode(['code'=>400,'msg'=>'缺少增长方式']);

        $standardInfo = db('standard')->find($standardId);
        if(empty($standardInfo)) return json_encode(['code'=>400,'msg'=>'暂未查询到相关产品']);

        if(empty($standardInfo['goods_id'])) return json_encode(['code'=>400,'msg'=>'产品缺少关联信息']);
        $goodsInfo = db('goods')->find($standardInfo['goods_id']);
        if($type=='inc'){
            $res = db('goods')->where('goods_id',$standardInfo['goods_id'])->setInc('goodssales',$salesVolume);
            $salesVolume = $goodsInfo['goodssales'] + $salesVolume;
        }elseif($type=='dec'){
            if($goodsInfo['goodssales'] < $salesVolume) return json_encode(['code'=>400,'msg'=>'销量不能小于0']);
            $res = db('goods')->where('goods_id',$standardInfo['goods_id'])->setDec('goodssales',$salesVolume);
            $salesVolume = $goodsInfo['goodssales'] - $salesVolume;
        }

        if($res){
            //更新ES的销量数据
            (new Esapi())->refreshStandardDataToES($standardId);
            return json_encode(['code'=>200,'msg'=>'更新成功','data'=>['salesVolume'=>$salesVolume]]);
        }else{
            return json_encode(['code'=>400,'msg'=>'更新失败']);
        }
    }
    //更新供应商的产品销量
    public function updateStandardSalesNoByGoodsId()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
    	}
        $goodsId = $post['goodsId']??0;
        $salesVolume = $post['salesVolume']??0;
        $type = $post['type']??"inc";
        if(empty($goodsId)) return json_encode(['code'=>400,'msg'=>'缺少商品ID']);
        if($salesVolume < 1) return json_encode(['code'=>400,'msg'=>'销量不能小于0']);
        if(!in_array($type,['inc','dec'])) return json_encode(['code'=>400,'msg'=>'缺少增长方式']);

        $goodsInfo = db('goods')->find($goodsId);
        if(empty($goodsInfo)) return json_encode(['code'=>400,'msg'=>'商品不存在']);
        if($type=='inc'){
            $res = db('goods')->where('goods_id',$goodsId)->setInc('goodssales',$salesVolume);
            $salesVolume = $goodsInfo['goodssales'] + $salesVolume;
        }elseif($type=='dec'){
            if($goodsInfo['goodssales'] < $salesVolume) return json_encode(['code'=>400,'msg'=>'销量不能小于0']);
            $res = db('goods')->where('goods_id',$goodsId)->setDec('goodssales',$salesVolume);
            $salesVolume = $goodsInfo['goodssales'] - $salesVolume;
        }
        if($res){
            $standardInfo = db('standard')->where('goods_id',$goodsId)->find();
            if(!empty($standardInfo['id'])){
                //更新ES的销量数据
                (new Esapi())->refreshStandardDataToES($standardInfo['id']);
            }
            return json_encode(['code'=>200,'msg'=>'更新成功','data'=>['salesVolume'=>$salesVolume]]);
        }else{
            return json_encode(['code'=>400,'msg'=>'更新失败']);
        }
    }
    //通过套餐信息获取供应商结算价和供应商分销价
    public function getCostAndPriceByStandardPackage()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $standardId = $post['standardId']??0;
        $supplierId = $post['supplierId']??"";
        $personIds = $post['personIds']??[];
        $date = $post['date']??"";

        //if(empty($personIds)) return json_encode(['code'=>400,'msg'=>'缺少规格ID集合']);

        $data = (new SD())->getCostAndPriceByStandardPersonIds($standardId,$supplierId,$personIds,$date);
        if(!empty($data)){
            //存在错误 会返回 code 码
            if(isset($data['code'])){
                return json_encode($data);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$data]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }

    public function getHotelRoomSkuPrice()
    {
        $data['checkInDate'] = '2020-10-01';
        $data['checkOutDate'] = '2020-10-03';
        $data['hotelId'] = '10014';
        $data['attrValues'] = [59];

        $result = (new HotelSpu())->searchRoomSku($data);
        if(is_array($result)){
            return $this->result('success',$result,200,'json');
        }else{
            return $this->result($result,[],-404,'json');
        }
    }

    public function getHotelSkuAttrs()
    {
        $data['hotelId'] = '10014';
        $result = (new HotelSpu())->getHotelSkuAttrs($data);
        if(is_array($result)){
            return $this->result('success',$result,200,'json');
        }else{
            return $this->result($result,[],-404,'json');
        }
    }

    //获取可选的产品推荐的集合 1 上架的标品
    public function getAllRecommendStandardList($supplier_id)
    {
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品
//        $topCate = (new SD())->getStandardTopCates();
//        $topCateIds = array_column($topCate,'id');
//        $where['s.topCate'] = ['in',$topCateIds];
        //是否允许其他人采购
        if(!empty($supplier_id)){//查询供应商自己产品和其他分销商允许采购的产品
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $supplier_admin_ids = implode(',',$supplier_admin_ids);
                $where[] = new Expression('s.supplier_admin_id in ('.$supplier_admin_ids.') or (s.supplier_admin_id not in ('.$supplier_admin_ids.') and s.allow_everyone_quote=1)');
            }else{
                $where['s.allow_everyone_quote'] = 1;//其他供应商允许售卖的产品
            }

        }else{//无供应商 通用
            $where['s.allow_everyone_quote'] = 1;//其他供应商允许售卖的产品
        }
        $standardList = db("standard s")->field("id,name")
            ->where($where)->select();

        return $standardList;

    }

    //获取已推荐的产品列表
    public function getRecommendStandardByStandardId($standardId,$from)
    {
        $recommendStandardIds = db('standardtrip st')->join('product p','p.id=st.trip_id','left')->field('p.recommend_standard_ids')->where('st.sid',$standardId)->find();
        if(empty($recommendStandardIds['recommend_standard_ids'])) return [];
        //按照参数的ids 进行排序
        $standardModel = new SD();
        $ids = explode(',',$recommendStandardIds['recommend_standard_ids']);
        $where['s.id'] = ['in',$ids];//选品IDS
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        $where['s.show_toB'] = 1;//用于toB的标品
        $list = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->join("supplier_admin admin",'admin.supplier_admin_id=s.supplier_admin_id','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,
            g.goods_id,g.goods_name,g.orderType,is_recommend,trip_id,
            startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,
            days,endDays,subType,toursLineTitle,specialInfo,topCate,admin.company_id as supplierId')
            ->where($where)
            ->order(new Expression('field(s.id,'.implode(',',$ids).')'))
            ->select();
        foreach ($list as $key=>$value){
            $list[$key]['id'] = $value['standardId'];
            $list[$key]['standardTypeName'] = $standardModel->getTypeName($value['standardType']);
            $list[$key]['classificationTags'] = $standardModel->getStandardTags($value['standardId']);
            $list[$key]['subType'] = $standardModel->getSubType($value['subType']);

            //获取关联的商品信息
            $list[$key]['goodsInfo'] = [];
            $list[$key]['showImg'] = "";
            if(!empty($value['goods_id'])){
                $list[$key]['goodsInfo'] = $standardModel->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                $image = $list[$key]['goodsInfo']['small_image']??[];
                $list[$key]['showImg'] = $standardModel->checkImgUrl($image[0]??"")??"";
//                $list[$key]['showImg'] = (new SD())->batchOssImgUrl($list[$key]['showImg']);
                $list[$key]['goodsprice'] = floatval($list[$key]['goodsInfo']['goodsprice'])??0;
                $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                unset($list[$key]['goodsInfo']['small_image']);
                $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
                $list[$key]['tags'] = !empty($list[$key]['goodsInfo']['tags'])?
                    array_merge($list[$key]['classificationTags'],$list[$key]['goodsInfo']['tags']):
                    $list[$key]['classificationTags'];
            }
        }

        return $list;
    }

    //订单系统采购商 获取上架的B端产品套餐
    public function getFeaturedProductPackages()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standard_id = $post['standard_id']??0;
        $supplier_id = $post['supplierId']??'';
        //判断是否供应商采购商同账号
        $model = new SD();
        $details = $model->getFeaturedGoodsPackageSpecByBuyer($standard_id,$supplier_id);
        if(!empty($details)){
            //存在错误 会返回 code 码
            if(isset($details['code'])){
                return json_encode($details);
            }else{
                return json_encode(['code'=>200,'msg'=>'获取成功','data'=>$details]);
            }
        }else{
            return json_encode(['code'=>400,'msg'=>'data is empty']);
        }
    }

    //增加产品的浏览量
    public function addGoodsViewCount(Request $request,$standard_id=0,$goods_id=0,$platform='')
    {
        $ip = $request->ip();
        $post = $request->param();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return $platform=='wap'?false:json_encode($auth_res);
        }elseif(!$auth_res){
            return $platform=='wap'?false:json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        if(empty($goods_id) && empty($standard_id)) return $platform=='wap'?false:json_encode(['code'=>400,'msg'=>'缺少GoodsId参数']);
        if(empty($platform)) return $platform=='wap'?false:json_encode(['code'=>400,'msg'=>'缺少platform参数']);
        if(!empty($standard_id)){
            $standard = db('standard')->find($standard_id);
            if(!empty($standard['goods_id'])) $goods_id = $standard['goods_id'];
        }elseif(!empty($goods_id)){

        }else{
            return $platform=='wap'?false:json_encode(['code'=>400,'msg'=>'缺少GoodsId参数']);
        }
        $goods = db('goods')->find($goods_id);
        if(empty($goods)) return $platform=='wap'?false:json_encode(['code'=>400,'msg'=>'no GoodsData']);

        $standard_id = 0;
        $standard = db('standard')->where(['goods_id'=>$goods_id])->find();
        if(!empty($standard['id'])){
            $standard_id = $standard['id']??0;
        }
        //验证是否重复浏览 单一IP五分钟一次
//        $limit_time = 5 * 60;
        $limit_time = 1;//一秒钟一次 解除限制
        $exist = db('goods_view_count_log')->where([
            'goods_id'=>$goods_id,
            'ip'=>$ip,
            'create_time'=>['gt',time() - $limit_time],
            'platform'=>$platform
        ])->find();

        if(!empty($exist)){
            return $platform=='wap'?false:json_encode(['code'=>400,'msg'=>$limit_time.'分钟内重复浏览不计数']);
        }
        db::startTrans();
        try{
            $this->recordGoodsViewCount($goods_id,$standard_id,$ip,$platform);
            db::commit();
            return $platform=='wap'?true:json_encode(['code'=>200,'msg'=>'success']);
        }catch (\Exception $e){
            db::rollback();
            return $platform=='wap'?false:json_encode(['code'=>400,'msg'=>$e->getMessage()]);
        }
    }

    //创建产品浏览量记录
    public function recordGoodsViewCount($goods_id,$standard_id,$ip,$platform){

        db('goods')->where(['goods_id'=>$goods_id])->setInc('view_count',1);
        if(!empty($standard_id)){
            db('standard')->where(['goods_id'=>$goods_id])->setInc('view_count',1);
        }
        return db('goods_view_count_log')->insert([
            'goods_id'=>$goods_id,
            'standard_id'=>$standard_id,
            'ip'=>$ip,
            'create_time'=>time(),
            'platform'=>$platform
        ]);
    }

    //增加产品的热度
    public function updateStandardLikeCount(Request $request)
    {
        $post = $request->param();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        if(empty($post['standardId'])) return json_encode(['code'=>400,'msg'=>'缺少standardId']);
        $standard = db('standard')->find($post['standardId']);
        if(empty($standard)) return json_encode(['code'=>400,'msg'=>'标品不存在']);

        $type = $post['type'] ?? 'inc';
        $number = $post['number'] ?? 1;

        db::startTrans();
        try{
            if($type == 'inc'){
                db('standard')->where(['id'=>$post['standardId']])->setInc('like_count',$number);
                $number = $standard['like_count'] + $number;
            }else{
                $number = min($number,$standard['like_count']);
                db('standard')->where(['id'=>$post['standardId']])->setDec('like_count',$number);
                $number = $standard['like_count'] - $number;
            }
            db::commit();
            return json_encode(['code'=>200,'msg'=>'success','data'=>['like_count'=>$number]]);
        }catch (\Exception $e){
            db::rollback();
            return json_encode(['code'=>400,'msg'=>$e->getMessage()]);
        }
    }

    //周统计
    public function statisticsWeek(Request $request,$start_day,$end_day)
    {
        if(empty($start_day)) return json_encode(['code'=>400,'msg'=>'请选择时间范围']);
        if(empty($end_day)) $end_day = date('Y-m-d');
        $start_day = min($start_day,$end_day);
        $end_day = max($start_day,$end_day);
        $start_time = strtotime($start_day);
        $end_time = strtotime($end_day);

        $newPublishProduct = $newOnSaleStandard = $supplierLogin = $productView = [];
        // 1 本周上架新品 2 本周推送 3 供应商登录平台 4 产品访问量排行
        $product_where['p.create_time'] = [['egt',$start_time],['lt',$end_time]];;
        $newPublishProduct = db('product p')->field('id as productId,name,item_num as productCode')->where($product_where)->select();
        $standard_where['s.show_tob'] = 1;
        $standard_where['s.status'] = 1;
        $standard_where['s.creattime'] = [['egt',$start_time],['lt',$end_time]];
        $newOnSaleStandard = db('standard s')
            ->join('goods g','g.goods_id=s.goods_id','left')
            ->join('product p','p.item_num=g.goods_tcode','left')
            ->field('s.name,s.id as standardId,s.goods_id as goodsId,g.supplier_id as g_supplier_id,p.supplier_id')
            ->where($standard_where)->select();
        $suppliers = (new Common())->getAllSupplierList();
        foreach ($newOnSaleStandard as $key=>$value){
            $newOnSaleStandard[$key]['supplierName'] = '未知';
            if(empty($value['supplier_id'])) $newOnSaleStandard[$key]['supplier_id'] = $value['supplier_id'] = $value['g_supplier_id'];
            unset($newOnSaleStandard[$key]['g_supplier_id']);
            foreach ($suppliers as $k=>$v){
                if($value['supplier_id']=='999999'){
                    $newOnSaleStandard[$key]['supplierName'] = '自营';break;
                }elseif($value['supplier_id']=='77777'){
                    $newOnSaleStandard[$key]['supplierName'] = '无';break;
                }elseif($value['supplier_id']=='1000000'){
                    $newOnSaleStandard[$key]['supplierName'] = '其他';break;
                }elseif($v['_id']==$value['supplier_id']){
                    $newOnSaleStandard[$key]['supplierName'] = $v['name'];break;
                }
            }
        }

        $newRecProduct = [];
        $log_where['l.create_time'] = [['egt',$start_time],['lt',$end_time]];
        $log_where['l.admin_menu_id'] = 25;//登入操作
        $supplierLogin = db('supplier_admin_log l')
            ->join('supplier_admin a','a.supplier_admin_id=l.admin_id','left')
            ->field('count(l.id) as count,l.admin_id,a.supplier_name,a.company_id')
            ->where($log_where)->group('l.admin_id')->select();
        $view_where['l.create_time'] = [['egt',$start_time],['lt',$end_time]];
        $productView = db('goods_view_count_log l')
            ->join('goods g','g.goods_id=l.goods_id','left')
            ->join('standard s','s.id = l.standard_id','left')
            ->field('l.goods_id,l.platform,l.standard_id,count(l.id) as count,
            g.goods_name,s.name as standard_name')
            ->where($view_where)
            ->group('l.goods_id,l.platform')
            ->select();
        $goodsViewIds = [];
        $productPlatView = [];
        foreach ($productView as $key=>$value){
            $index = array_search($value['goods_id'],$goodsViewIds);
            if($index!==false){
                $productPlatView[$index][$value['platform']] = $value['count'];
            }else{
                $goodsViewIds[] = $value['goods_id'];
                $value['name'] = empty($value['standard_name'])?$value['goods_name']:$value['standard_name'];
                unset($value['goods_name'],$value['standard_name']);
                $value['wap'] = $value['wxsoft'] = $value['agent'] = 0;
                $value[$value['platform']] = (int)$value['count'];
                $productPlatView[] = $value;
            }
        }
        foreach ($productPlatView as $key=>$value){
            $productPlatView[$key]['total'] = $value['wap'] + $value['agent'] + $value['wxsoft'];
            unset($productPlatView[$key]['platform'],$productPlatView[$key]['count']);
        }
        //截止目前上架的产品数量和供应商
        $standard_total_where['s.show_tob'] = 1;
        $standard_total_where['s.status'] = 1;
        $newOnSaleStandardByNow = db('standard s')
            ->join('goods g','g.goods_id=s.goods_id','left')
            ->join('product p','p.item_num=g.goods_tcode','left')
            ->field('s.name,s.id as standardId,s.goods_id as goodsId,g.supplier_id as g_supplier_id,p.supplier_id')
            ->where($standard_total_where)->select();
        $newOnSaleStandardTotal['newStandardCount'] = count($newOnSaleStandardByNow);
        foreach ($newOnSaleStandardByNow as $key=>$value){
            $newOnSaleStandardByNow[$key]['supplierName'] = '未知';
            if(empty($value['supplier_id'])) $newOnSaleStandardByNow[$key]['supplier_id'] = $value['supplier_id'] = $value['g_supplier_id'];
            unset($newOnSaleStandardByNow[$key]['g_supplier_id']);
        }
        //排除掉未知供应商
        $supplierCount = array_unique(array_filter(array_column($newOnSaleStandardByNow,'supplier_id')));
        $newOnSaleStandardTotal['supplierCount'] = count($supplierCount);
        $data = [
            'newOnSaleStandardTotal'=>$newOnSaleStandardTotal,
            'newPublishProduct'=>$newPublishProduct,
            'newOnSaleStandard'=>$newOnSaleStandard,
            'newRecProduct'=>$newRecProduct,
            'supplierLogin'=>$supplierLogin,
            'productView'=>$productPlatView,
        ];
        return json_encode(['code'=>200,'msg'=>'success','data'=>$data]);
    }

    //定时提醒产品日期到期提醒
    public function noticeSalesDate($start_date='',$sendWx='',$sendEmail='')
    {
        trace('产品价格日期到期预警接口');
        if(!config('OPEN_NOTICE_SALESDATA')) return json_encode(['code'=>-404,'msg'=>'暂未开启产品价格日期到期预警']);
        ignore_user_abort();//忽略用户操作
        set_time_limit(0);//程序不终止
        //提前日期
        if(empty($start_date)) $start_date = date('Y-m-d');
        $notice_day = 7;
        $notice_date = date('Y-m-d',strtotime('+'.$notice_day.' days',strtotime($start_date)));
        //超期产品
        $goodsData = $this->getNoticeGoodsData($notice_date);
        try{
            $goodsData = $this->needNoticeGoodsData($goodsData,$start_date);
            if(empty($goodsData)) return json_encode(['code'=>-404,'msg'=>'暂无产品到期预警']);
            $noticeData = [];
            foreach ($goodsData as $value){
                $noticeData[] = $value['product'];
            }
            //发送企业微信提醒
            if($sendWx && !empty($noticeData)) (new KbxOrder())->preToBSalesExpireDateNotifyV3($noticeData);
            //发送邮件提醒
            if($sendEmail && !empty($goodsData)){
                $this->sendEmailNoticeProductSalesDate($goodsData);
                //发送供应商邮件
                $supplierGoodsData = $this->getSupplierNoticeGoodsData($goodsData);
                foreach ($supplierGoodsData as $value){
                    if(!empty($value['goodsData'])) $this->sendEmailNoticeProductSalesDateToSupplier($value);
                }
            }

            return json_encode(['code'=>200,'msg'=>'success','data'=>$goodsData]);
        }catch (\Exception $e){
            return json_encode(['code'=>-404,'msg'=>$e->getMessage()]);
        }
    }
    //产品到期自动下架
    public function expiredProductAutoDownSales($sendEmail='')
    {
        trace('产品到期自动下架接口');
        if(!config('OPEN_AUTODOWNSALES_STANDARD')) return json_encode(['code'=>-404,'msg'=>'暂未开启产品到期自动下架']);
        ignore_user_abort();//忽略用户操作
        set_time_limit(0);//程序不终止
        $notice_date = date('Y-m-d');
        $goodsData = $this->getNoticeGoodsData($notice_date);
        //产品下架操作
        foreach ($goodsData as $key=>$value){
            $res = $this->downSaleStandard($value['standardId']);
            if(!$res){
                unset($goodsData[$key]);
            }
        }
        //发送下架邮件
        if($sendEmail && !empty($goodsData)){
            $this->sendEmailNoticeExpiredProductAutoDownSales($goodsData);
            //发送供应商邮件
            $supplierGoodsData = $this->getSupplierNoticeGoodsData($goodsData);
            foreach ($supplierGoodsData as $value){
                if(!empty($value['goodsData'])) $this->sendEmailNoticeExpiredProductAutoDownSalesToSupplier($value);
            }
        }

        return json_encode(['code'=>200,'msg'=>'success','data'=>$goodsData]);
    }
    //供应商邮件提醒产品到期
    public function sendEmailNoticeProductSalesDateToSupplier($supplierGoodsData){
        if(empty($supplierGoodsData['goodsData'])) return false;
        $subject = '产品售卖到期 下架预警通知';
        $day = ceil(strtotime($supplierGoodsData['minDate']) - ( strtotime(date('Y-m-d'))) / (24 * 3600) );
        $content = '您在快帮行资源服务平台上架的商品快到售卖截止日期，最近的商品将会在'.$day.'天后被下架。如需继续售卖，请登录快帮行供应商后台调整产品售卖时段。有产品相关问题，可以微信咨询 kbxmei。<br>产品信息如下：<br>';

        foreach ($supplierGoodsData['goodsData'] as $value){
            $content .= '名称：'.$value['product']['productName'].'，编号：【'.$value['product']['productCode'].'】，截止日期：【'.$value['product']['salesExpireDate'].'】<br>';
        }
        trace('供应商邮件提醒产品到期预警:'.$subject.'--'.$content.'--'.$supplierGoodsData['address']);
        if(!empty($supplierGoodsData['address'])) (new WapNotify())->kbxemailcode($subject,$content,$supplierGoodsData['address']);
    }

    //内部邮件提醒产品到期
    public function sendEmailNoticeProductSalesDate($goodsData){
        if(empty($goodsData)) return false;
        $subject = '产品日期价格预警通知';
        $content = '【快帮行】日期价格到期预警的产品信息如下：<br>';

        foreach ($goodsData as $value){
            $content .= '名称：'.$value['product']['productName'].'，编号：【'.$value['product']['productCode'].'】，截止日期：【'.$value['product']['salesExpireDate'].'】<br>';
        }
        $address = config('DEFAULT_NOTICE_EMAIL');
        (new WapNotify())->kbxemailcode($subject,$content,$address);
    }

    //供应商邮件提醒产品下架
    public function sendEmailNoticeExpiredProductAutoDownSalesToSupplier($supplierGoodsData){
        if(empty($supplierGoodsData['goodsData'])) return false;
        $subject = '产品下架通知';
        $content = '【快帮行】日期价格到期自动下架的产品信息如下：<br>';

        foreach ($supplierGoodsData['goodsData'] as $value){
            $content .= '名称：'.$value['product']['productName'].'，编号：【'.$value['product']['productCode'].'】，截止日期：【'.$value['product']['salesExpireDate'].'】<br>';
        }
        trace('供应商邮件提醒产品下架:'.$subject.'--'.$content.'--'.$supplierGoodsData['address']);
        if(!empty($supplierGoodsData['address'])) (new WapNotify())->kbxemailcode($subject,$content,$supplierGoodsData['address']);
    }

    //内部邮件提醒产品下架
    public function sendEmailNoticeExpiredProductAutoDownSales($goodsData){
        if(empty($goodsData)) return false;
        $subject = '产品下架通知';
        $content = '【快帮行】日期价格到期自动下架的产品信息如下：<br>';

        foreach ($goodsData as $value){
            $content .= '名称：'.$value['product']['productName'].'，编号：【'.$value['product']['productCode'].'】，截止日期：【'.$value['product']['salesExpireDate'].'】<br>';
        }
        $address = config('DEFAULT_NOTICE_EMAIL');
        (new WapNotify())->kbxemailcode($subject,$content,$address);
    }

    //获取超过特定售卖日期的产品
    public function getNoticeGoodsData($notice_date,$includeGroupExhibition=true)
    {
        if(empty($notice_date)) return false;
        $limit = 5;
        //1 获取所有设置了价格的产品的最后日期
        $base_mode_price = db('product_base_dailyprice')
            ->where(['product_id'=>['gt',0]])
            ->field('product_id,max(time) as date,"base_mode" as mode')
            ->group('product_id')->select();
        //排除未超期的产品
        $base_mode_pids = array_column($base_mode_price,'product_id');
        foreach ($base_mode_price as $key=>$value){
            if($value['date'] >= $notice_date){
                unset($base_mode_price[$key]);
            }
        }
        $normal_mode_price = db('product_dailyprice')
            ->where(['product_id'=>[['gt',0],['not in',$base_mode_pids]]])
            ->field('product_id,max(time) as date,"pro_mode" as mode')
            ->group('product_id')->select();
        $normal_mode_pids = array_column($normal_mode_price,'product_id');
        $base_mode_pids = array_merge($base_mode_pids,$normal_mode_pids);
        foreach ($normal_mode_price as $key=>$value){
            if($value['date'] >= $notice_date){
                unset($normal_mode_price[$key]);
            }
        }
        //排除已匹配的商品ID
        $exclude_goods_ids = db('product p')->join('goods g','g.goods_tcode=p.item_num')
            ->where(['p.id'=>['in',$base_mode_pids]])->column('g.goods_id');
        $goods_mode_price = db('personday')
            ->where(['goods_id'=>[['gt',0],['not in',$exclude_goods_ids]]])
            ->field('goods_id,max(time) as date,"goods_mode" as mode')
            ->group('goods_id')->select();
        foreach ($goods_mode_price as $key=>$value){
            if($value['date'] >= $notice_date){
                unset($goods_mode_price[$key]);
            }
        }
        //合并 $base_mode_price $normal_mode_price
        $base_mode_pids = array_column($base_mode_price,'product_id');
        foreach ($normal_mode_price as $key=>$value){
            if(!in_array($value['product_id'],$base_mode_pids)){
                $base_mode_price[] = $value;
            }
        }
        $product_ids = array_column($base_mode_price,'product_id');
        $goods = db('product p')->join('goods g','g.goods_tcode=p.item_num')
            ->where(['p.id'=>['in',$product_ids]])
            ->field('p.id,g.goods_id')->select();

        foreach ($base_mode_price as $key=>$value){
            $base_mode_price[$key]['goods_id'] = 0;
            foreach ($goods as $k=>$v){
                if($value['product_id']==$v['id']){
                    $base_mode_price[$key]['goods_id'] = $v['goods_id'];break;
                }
            }
        }
        //合并 $base_mode_price $goods_mode_price
        $base_mode_goods_ids = array_column($base_mode_price,'goods_id');
        foreach ($goods_mode_price as $key=>$value){
            if(!in_array($value['goods_id'],$base_mode_goods_ids)){
                $base_mode_price[] = $value;
            }
        }
        //2 筛选出上架的产品
        $filter_standard_where['status'] = 1;
        $filter_standard_where['show_tob'] = 1;
        if($includeGroupExhibition){
            $filter_standard_where['allow_everyone_quote'] = ['exp',
                new Expression(' = 1 or (allow_everyone_quote = 0 and is_group_exhibition = 0)')];
        }
        $upGoods = db('standard')
            ->where($filter_standard_where)->column('goods_id');
        if(empty($upGoods)) return [];
        //3 获取产品信息并发送价格提醒

        foreach ($base_mode_price as $key=>$value){
            if(!in_array($value['goods_id'],$upGoods)){
                unset($base_mode_price[$key]);
            }
        }

        $goods_ids = array_column($base_mode_price,'goods_id');
        //需要包装的请求体
        $where['g.goods_id'] = ['in',$goods_ids];
        $goodsData = db('goods g')
            ->join('city c','c.id=g.city_id','left')
            ->join('product p','p.item_num=g.goods_tcode','left')
            ->join('standard s','s.goods_id=g.goods_id','left')
            ->field('g.goods_id,g.goods_name,g.orderType,p.name as product_name,p.supplier_admin_id,
            c.name as city_name,p.supplier_id,g.goods_tcode,g.code,s.id as standardId')
            ->where($where)
            ->limit($limit)
            ->order('g.goods_id desc')
            ->select();
        $supplierList = (new Common())->getSupplierList();
        foreach ($goodsData as $key=>$value){
            $goodsData[$key]['mode'] = '';
            $goodsData[$key]['salesExpireDate'] = '';
            $goodsData[$key]['product'] = [
                'productCode'=>empty($value['goods_tcode'])?$value['code']:$value['goods_tcode'],
                'standardId'=>$value['standardId'],
                'city'=>$value['city_name'],
                'serviceType'=>$value['orderType'],
                'productName'=>empty($value['goods_tcode']) ?
                    $value['goods_name'] : (
                        empty($value['product_name']) ?
                            ($value['goods_name']?:"") : $value['product_name']
                    ),
                'salesExpireDate'=>'',
                'supplier'=>''
            ];

            foreach ($base_mode_price as $k=>$v){
                if($value['goods_id']==$v['goods_id']){
                    $goodsData[$key]['product']['salesExpireDate'] = $v['date'];
                    $goodsData[$key]['salesExpireDate'] = $v['date'];
                    $goodsData[$key]['mode'] = $v['mode'];
                    break;
                }
            }
            foreach ($supplierList as $supplier){
                if($value['supplier_id']==$supplier['id']){
                    $goodsData[$key]['product']['supplier'] = $supplier['name'];
                    break;
                }
            }
        }
        //按照日期倒排
        if(!empty($goodsData)){
            $sort_date = array_column($goodsData,'salesExpireDate');
            array_multisort($sort_date,SORT_DESC,$goodsData);
        }

        return $goodsData;
    }

    //过滤需要发送的产品ID
    public function needNoticeGoodsData($goodsData,$start_date='')
    {
        if(!empty($start_date)){
            $now_time = strtotime($start_date);
        }else{
            $now_time = time();
        }
        $cacheNoticeExpiredGoodsData = Cache::get('notice_expired_goods');
        if(empty($cacheNoticeExpiredGoodsData)){
            foreach ($goodsData as $k=>$v){
                if(strtotime($v['salesExpireDate']) - $now_time > 24*3600){
                    $cacheNoticeExpiredGoodsData[] = [
                        'goods_id'=>$v['goods_id'],
                        'salesExpireDate'=>$v['salesExpireDate']
                    ];
                }
            }
        }else{
            //优先将过期时间更新
            foreach ($cacheNoticeExpiredGoodsData as $k=>$v){
                //离截止日期还有一天 删除此数据
                if(strtotime($v['salesExpireDate']) - $now_time <= 24*3600){
                    unset($cacheNoticeExpiredGoodsData[$k]);
                }
            }
            $cache_goods_id = [];
            if(!empty($cacheNoticeExpiredGoodsData)){
                $cache_goods_id = array_column($cacheNoticeExpiredGoodsData,'goods_id');
            }
            foreach ($goodsData as $key=>$value){
                if(!in_array($value['goods_id'],$cache_goods_id)){
                    if(strtotime($value['salesExpireDate']) - $now_time > 24*3600){
                        $cacheNoticeExpiredGoodsData[] = [
                            'goods_id'=>$value['goods_id'],
                            'salesExpireDate'=>$value['salesExpireDate']
                        ];
                    }
                }else{
                    unset($goodsData[$key]);
                }
            }
        }

        Cache::set('notice_expired_goods',$cacheNoticeExpiredGoodsData?:null);

        return $goodsData;
    }

    public function getSupplierNoticeGoodsData($goodsData)
    {
        if(empty($goodsData)) return [];

        $supplier_admin_ids = array_unique( array_filter(array_column($goodsData,'supplier_admin_id')) );
        if(empty($supplier_admin_ids)) return [];
        $supplierAdmin = db('supplier_admin')->field('supplier_admin_id,supplier_account as address')->where([
            'supplier_admin_id'=>['in',$supplier_admin_ids]
        ])->select();
        if(empty($supplierAdmin)) return [];

        foreach ($supplierAdmin as $key=>$value){
            $supplierAdmin[$key]['goodsData'] = [];
            $supplierAdmin[$key]['minDate'] = date('Y-m-d');
            foreach ($goodsData as $k=>$v){
                if($v['supplier_admin_id']==$value['supplier_admin_id']){
                    $supplierAdmin[$key]['goodsData'][] = $v;
                    $supplierAdmin[$key]['minDate'] = min($supplierAdmin[$key]['minDate'],$v['salesExpireDate']);
                }
            }
        }

        return $supplierAdmin;
    }

    public function getCacheNoticeExpiredGoodsData($clear=false)
    {
        if($clear) Cache::set('notice_expired_goods',null);
        return json_encode(Cache::get('notice_expired_goods'));
    }

    //下架标品
    public function downSaleStandard($standardId)
    {
        if(empty($standardId)) return false;
        $standard = db('standard')->find($standardId);
        $standardTrip = db('standardtrip')->where(['sid'=>$standardId])->find();
        if(empty($standard)) return false;
        db::startTrans();
        try{
            db("standard")->where(['id'=>$standardId])->update([
                'show_toB'=>0
            ]);
            if(!empty($standardTrip['trip_id'])){
                db('product')->where('id',$standardTrip['trip_id'])->update([
                    'check_status'=>0
                ]);
            }
            db::commit();
        }catch (\Exception $e){
            db::rollback();
            trace('产品自动下架失败,'.$e->getMessage());
            return false;
        }

        //es 删除该商品
        (new Esapi())->delStandardDoc($standardId);
        //通知相应供应商下架该商品
        (new KbxOrder())->pullOffShelvesNotifyToKbx($standardId);
        //服务号通知供应商下架通知
        (new KbxOrder())->sendProductOffAlertNotify($standard);
        return true;
    }

    //更新标品库存
    public function updateStandardStock()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $goods_id = $post['goodsId']??0;
        $packages = $post['packages']??'';
        $type = $post['type']??'';
        if(empty($goods_id)) return json_encode(['code'=>400,'msg'=>'缺少参数goodsId']);
        if(empty($packages)) return json_encode(['code'=>400,'msg'=>'缺少参数packages']);
        if(empty($type)) return json_encode(['code'=>400,'msg'=>'缺少参数type']);

        $res = (new SD())->updateStandardStock($goods_id,$packages,$type);
        if($res){
            return json_encode(['code'=>200,'msg'=>'库存更新成功']);
        }else{
            return json_encode(['code'=>400,'msg'=>'库存更新失败']);
        }
    }

    //更新标品库存
    public function updateStandardStockBySupplier()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $goods_id = $post['goodsId']??0;
        $packages = $post['packages']??'';
        $type = $post['type']??'';
        if(empty($goods_id)) return json_encode(['code'=>400,'msg'=>'缺少参数goodsId']);
        if(empty($packages)) return json_encode(['code'=>400,'msg'=>'缺少参数packages']);
        if(empty($type)) return json_encode(['code'=>400,'msg'=>'缺少参数type']);
        $packages = json_decode($packages,true);
        $res = (new SD())->updateStandardStock($goods_id,$packages,$type);
        if($res){
            return json_encode(['code'=>200,'msg'=>'库存更新成功']);
        }else{
            return json_encode(['code'=>400,'msg'=>'库存更新失败']);
        }
    }

    //测试专用 获取特定日期前的需要延期的产品
    public function getNoticeGoodsDataApi($notice_date)
    {
        $result = $this->getNoticeGoodsData($notice_date);
        return $this->result('success',$result,200,'json');
    }
    //测试查看不需要同步		
    public function productData()
    {
        $file = APP_PATH.'logs/productInfo.json';
        $conetnt = file_get_contents($file);
//        return $conetnt;
        $array = json_decode($conetnt,true);
        $data = $array['data'];
        $result = [];
        foreach ($data as $value){
            $result[] = $value['product'];
//            $product = $value['product'];
//            $result[] = '名称：'.$product['productName'].
//                '--编号：'.$product['productCode'].
//                '--供应商：'.$product['supplier'].
//                '--截止日期：'.$product['salesExpireDate'];
        }

        $table_head = array("产品编号","标品ID","城市","服务类型","产品名称","过期时间","供应商");
        (new ExportExcel())->exportExcel($result, $table_head, "即将过期产品列表");
    }

    //智慧导览小程序 旅游攻略列表
    public function travelGuides(Request $request)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        //$supplier_id = $post['supplierId']??0;
        //if(empty($supplier_id)) return json_encode(['code'=>400,'msg'=>'缺少supplierId']);
        //$supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
        //$where['supplier_admin_id'] = ['in',$supplier_admin_ids];
        $page = $post['page']??1;
        $pageLimit = $post['pageLimit']??20;
        $where['is_delete'] = 0;
        if(!empty($post['keywords'])){
            $where['id|title|description'] = ['like','%'.$post['keywords'].'%'];
        }
        if(!empty($post['category'])){
            $where['category'] = $post['category'];
        }
        $result = (new SD())->listGuide($where,$page,$pageLimit);

        return json_encode(['code'=>200,'msg'=>'success','data'=>$result]);
    }

    //智慧导览小程序 旅游攻略详情
    public function travelGuideInfo(Request $request)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

//        $supplier_id = $post['supplierId']??'';
        $guide_id = $post['guideId']??'';
//        if(empty($supplier_id)) return json_encode(['code'=>400,'msg'=>'缺少supplierId']);
        if(empty($guide_id)) return json_encode(['code'=>400,'msg'=>'缺少guideId']);

//        $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
        $result = (new SD())->infoGuide($guide_id);
        if(!empty($result)){
            return json_encode(['code'=>200,'msg'=>'success','data'=>$result]);
        }else{
            return json_encode(['code'=>400,'msg'=>'无权限或资源不存在']);

        }
    }

    public function incBrowseTravelGuide()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $guide_id = $post['guideId']??'';
        if(empty($guide_id)) return json_encode(['code'=>400,'msg'=>'缺少guideId']);

        $result = (new SD())->incBrowseByGuideId($guide_id);
        if(!empty($result)){
            return json_encode(['code'=>200,'msg'=>'success','data'=>$result]);
        }else{
            return json_encode(['code'=>400,'msg'=>'failed']);

        }

    }

    //智慧导览小程序 选择旅游攻略后的列表
    public function getTravelGuidesByGuideIds($page=1,$pageLimit=10)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $ids = $post['ids']??[];
        if(empty($ids)) return json_encode(['code'=>400,'msg'=>'缺少选品IDs']);

        $where['id'] = ['in',$ids];
        //增加筛选条件
        $keyword = !empty($post['keywords'])?trim($post['keywords']):'';
        $supplier_id = $post['supplierId']??'';
        $category = $post['caetgory']??'';
        if(!empty($category)){
            $where['category'] = $category;
        }
        //$allData = $post['allData']??'';//默认只返回上架数据
        //关键词搜索
        if(!empty($keyword)) $where['id|title|description'] = ['like','%'.$post['keywords'].'%'];
        //特定供应商的产品
        if(!empty($supplier_id)){
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $where['supplier_admin_id'] = ['in',$supplier_admin_ids];
            }
        }
        $where['is_delete'] = 0;
        //按照参数的ids 进行排序
        $order_desc = new Expression('field(id,'.implode(',',$ids).')');
        $result = (new SD())->listGuide($where,$page,$pageLimit,$order_desc);

        //返回json 数据
        return $this->result('success',$result,200,'json');
    }

    //订单系统采购商 获取选品后的产品列表
    public function getVirtualStandardListByStandardIds($page=1,$offset=10)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $ids = $post['ids']??[];
        if(empty($ids)) return json_encode(['code'=>400,'msg'=>'缺少选品IDs']);

        //增加筛选条件
        $keyword = !empty($post['keywords'])?trim($post['keywords']):'';
        $cityKbxIds = $post['cityIds']??[];
        $countryKbxIds = $post['countryIds']??[];
        $continentIds = $post['continentIds']??[];
        $tagIds = $post['tagIds']??[];
        $supplier_id = $post['supplierId']??'';
        $allData = $post['allData']??'';//默认只返回上架数据
        $latLng = $post['latLng']??'';//基于经纬度进行hash
        //关键词搜索
        if(!empty($keyword)) $where['s.id|s.name|g.goods_tcode'] = ['like','%'.$keyword.'%'];
        //出发城市
        if(!empty($cityKbxIds)){//城市级筛选
            $cityIds = db('city')->where(['kbx_id'=>['in',$cityKbxIds]])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }elseif(!empty($countryKbxIds)){//国家级筛选
            $countryIds = db('city')->where(['kbx_id'=>['in',$countryKbxIds]])->column('id');
            if(!empty($countryIds)){
                $cityIds = db('city')->where([
                    'groupid'=>['in',$countryIds],
                    'deleted'=>0,
                    'type'=>'CITY'
                ])->column('id');
                if(!empty($countryIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
            }
        }elseif(!empty($continentIds)){//洲级筛选
            $cityIds = db('city')->where([
                'continentid'=>['in',$continentIds],
                'deleted'=>0,
                'type'=>'CITY'
            ])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }
//        var_dump($cityIds);exit;
        //分类类型
        if(!empty($tagIds)){
            $standard_ids = (new SD())->getStandardIdsBytagIds($tagIds);
            $where['s.id'] = [['in',$ids],['in',$standard_ids]];
        }else{
            $where['s.id'] = ['in',$ids];//选品IDS
        }
        //特定供应商的产品
        if(!empty($supplier_id)){
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
            }
        }

        if(!empty($latLng)){
            list($req_lat,$req_lng) = explode(',',$latLng);
            if(!empty($req_lat) && !empty($req_lng)){
                $geohash = GeoHash::encode($req_lng,$req_lat);
//                if(!empty($geohash)) $where['pe.electronic_scenic_geohash'] = ['like',substr($geohash,0,3).'%'];
            }
        }
        //按照参数的ids 进行排序
        $standardModel = new SD();
        $from = 'orderSystem';
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        if(empty($allData)) $where['s.show_toB'] = 1;//用于toB的标品
//        $topCate = (new SD())->getStandardTopCates();
//        $topCateIds = array_column($topCate,'id');
//        $where['s.topCate'] = ['in',$topCateIds];

        //只针对虚拟产品
        $where['g.orderType'] = 'VirtualProduct';
        $total = $list = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("product_electronic pe",'pe.electronic_pro_id=st.trip_id','left')
            ->where($where)
            ->count();
        $allList = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->join("product_electronic pe",'pe.electronic_pro_id=st.trip_id','left')
            ->join("supplier_admin admin",'admin.supplier_admin_id=s.supplier_admin_id','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,
            g.goods_id,g.goods_name,g.orderType,is_recommend,trip_id,
            startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,
            days,endDays,subType,toursLineTitle,specialInfo,topCate,admin.company_id as supplierId,
            pe.electronic_scenic_latlng')
            ->where($where)
            ->order(new Expression('field(s.id,'.implode(',',$ids).')'))
            //->page($page,$offset)
            ->select();
        if(!empty($allList)){
            foreach ($allList as $key=>$value){
                $allList[$key]['distance'] = 999999;
                if(!empty($value['electronic_scenic_latlng']) && !empty($geohash)){
                    $product_scenic_latlng = json_decode($value['electronic_scenic_latlng'],true);
                    $distance = (new Poi())->getDistance($req_lat,$req_lng,$product_scenic_latlng['lat'],$product_scenic_latlng['lng']);
                    $allList[$key]['distance'] = sprintf('%.2f',$distance);
                }
            }
            //多维数组按照距离排序
            $distance_column = array_column($allList,'distance');
            array_multisort($distance_column,SORT_ASC,$allList);
            $list = array_slice($allList,$offset*($page-1),$offset);
            foreach ($list as $key=>$value){
                $list[$key]['id'] = $value['standardId'];
                $list[$key]['goods_name'] = $value['standardName'];
                $list[$key]['standardTypeName'] = $standardModel->getTypeName($value['standardType']);
                $list[$key]['classificationTags'] = $standardModel->getStandardTags($value['standardId']);
                $list[$key]['subType'] = $standardModel->getSubType($value['subType']);
                $list[$key]['distance'] = 999999;
                if(!empty($value['electronic_scenic_latlng']) && !empty($geohash)){
                    $product_scenic_latlng = json_decode($value['electronic_scenic_latlng'],true);
                    $distance = (new Poi())->getDistance($req_lat,$req_lng,$product_scenic_latlng['lat'],$product_scenic_latlng['lng']);
                    $list[$key]['distance'] = sprintf('%.2f',$distance);
                }
                //获取关联的商品信息
                $list[$key]['goodsInfo'] = [];
                $list[$key]['showImg'] = "";
                if(!empty($value['goods_id'])){
                    $list[$key]['goodsInfo'] = $standardModel->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                    $image = $list[$key]['goodsInfo']['small_image']??[];
                    $list[$key]['showImg'] = $standardModel->checkImgUrl($image[0]??"")??"";
//                $list[$key]['showImg'] = (new SD())->batchOssImgUrl($list[$key]['showImg']);
                    $list[$key]['goodsprice'] = floatval($list[$key]['goodsInfo']['goodsprice'])??0;
                    $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                    unset($list[$key]['goodsInfo']['small_image']);
                    $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                    $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                    $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
                    $list[$key]['tags'] = !empty($list[$key]['goodsInfo']['tags'])?
                        array_merge($list[$key]['classificationTags'],$list[$key]['goodsInfo']['tags']):
                        $list[$key]['classificationTags'];
                }
            }
        }else{
            $list = [];
        }


        $result['pageInfo'] = [
            'totalNum'=>$total,
            'totalPage'=>ceil($total/$offset),
            'page'=>(int)$page,
            'offset'=>(int)$offset,
        ];
        $result['list'] = $list;
        //返回json 数据
        return $this->result('success',$result,200,'json');
    }

    public function getVirtualStandardListByStandardIdsTest($page=1,$offset=10)
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }
        $ids = $post['ids']??[];
        if(empty($ids)) return json_encode(['code'=>400,'msg'=>'缺少选品IDs']);

        //增加筛选条件
        $keyword = !empty($post['keywords'])?trim($post['keywords']):'';
        $cityKbxIds = $post['cityIds']??[];
        $countryKbxIds = $post['countryIds']??[];
        $continentIds = $post['continentIds']??[];
        $tagIds = $post['tagIds']??[];
        $supplier_id = $post['supplierId']??'';
        $allData = $post['allData']??'';//默认只返回上架数据
        $latLng = $post['latLng']??'';//基于经纬度进行hash
        //关键词搜索
        if(!empty($keyword)) $where['s.id|s.name|g.goods_tcode'] = ['like','%'.$keyword.'%'];
        //出发城市
        if(!empty($cityKbxIds)){//城市级筛选
            $cityIds = db('city')->where(['kbx_id'=>['in',$cityKbxIds]])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }elseif(!empty($countryKbxIds)){//国家级筛选
            $countryIds = db('city')->where(['kbx_id'=>['in',$countryKbxIds]])->column('id');
            if(!empty($countryIds)){
                $cityIds = db('city')->where([
                    'groupid'=>['in',$countryIds],
                    'deleted'=>0,
                    'type'=>'CITY'
                ])->column('id');
                if(!empty($countryIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
            }
        }elseif(!empty($continentIds)){//洲级筛选
            $cityIds = db('city')->where([
                'continentid'=>['in',$continentIds],
                'deleted'=>0,
                'type'=>'CITY'
            ])->column('id');
            if(!empty($cityIds)) $where['st.startCityId|s.startCity'] = ['in',$cityIds];
        }
//        var_dump($cityIds);exit;
        //分类类型
        if(!empty($tagIds)){
            $standard_ids = (new SD())->getStandardIdsBytagIds($tagIds);
            $where['s.id'] = [['in',$ids],['in',$standard_ids]];
        }else{
            $where['s.id'] = ['in',$ids];//选品IDS
        }
        //特定供应商的产品
        if(!empty($supplier_id)){
            //获取管理员ID
            $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
            if(!empty($supplier_admin_ids)){
                $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
            }
        }

        if(!empty($latLng)){
            list($req_lat,$req_lng) = explode(',',$latLng);
            if(!empty($req_lat) && !empty($req_lng)){
                $geohash = GeoHash::encode($req_lng,$req_lat);
//                if(!empty($geohash)) $where['pe.electronic_scenic_geohash'] = ['like',substr($geohash,0,3).'%'];
            }
        }
        //按照参数的ids 进行排序
        $standardModel = new SD();
        $from = 'orderSystem';
        $where['s.status'] = 1;//启用的标品
        $where['s.is_deleted'] = 0;//未删除的标品
        if(empty($allData)) $where['s.show_toB'] = 1;//用于toB的标品
//        $topCate = (new SD())->getStandardTopCates();
//        $topCateIds = array_column($topCate,'id');
//        $where['s.topCate'] = ['in',$topCateIds];

        //只针对虚拟产品
        $where['g.orderType'] = 'VirtualProduct';
        $total = $list = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("product_electronic pe",'pe.electronic_pro_id=st.trip_id','left')
            ->where($where)
            ->count();
        $start_time = microtime(true);
        $list = db("standard s")
            ->join("goods g",'g.goods_id=s.goods_id','left')
            ->join("standardtrip st",'st.sid=s.id','left')
            ->join("city c",'c.id=st.startCityId','left')
            ->join("product_electronic pe",'pe.electronic_pro_id=st.trip_id','left')
            ->join("supplier_admin admin",'admin.supplier_admin_id=s.supplier_admin_id','left')
            ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,
            g.goods_id,g.goods_name,g.orderType,is_recommend,trip_id,
            startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,
            days,endDays,subType,toursLineTitle,specialInfo,topCate,admin.company_id as supplierId,
            pe.electronic_scenic_latlng')
            ->where($where)
            ->order(new Expression('field(s.id,'.implode(',',$ids).')'))
            //->page($page,$offset)
            ->select();
        $allList = $list;
        var_dump('获取数据：',microtime(true) - $start_time);
        for ($i = 0; $i < 200; $i++){
            $allList = array_merge($allList,$list);
            $total = count($allList);
        }
        var_dump('合并数据：',microtime(true) - $start_time);

        foreach ($allList as $key=>$value){
            $allList[$key]['distance'] = 999999;
            if(!empty($value['electronic_scenic_latlng']) && !empty($geohash)){
                $product_scenic_latlng = json_decode($value['electronic_scenic_latlng'],true);
                $distance = (new Poi())->getDistance($req_lat,$req_lng,$product_scenic_latlng['lat'],$product_scenic_latlng['lng']);
                $allList[$key]['distance'] = sprintf('%.2f',$distance);
            }
        }
        //多维数组按照距离排序
        $distance_column = array_column($allList,'distance');
        array_multisort($distance_column,SORT_ASC,$allList);
        $list = array_slice($allList,$offset*($page-1),$offset);
        var_dump('数据排序：',microtime(true) - $start_time);

        foreach ($list as $key=>$value){
            $list[$key]['id'] = $value['standardId'];
            $list[$key]['goods_name'] = $value['standardName'];
            $list[$key]['standardTypeName'] = $standardModel->getTypeName($value['standardType']);
            $list[$key]['classificationTags'] = $standardModel->getStandardTags($value['standardId']);
            $list[$key]['subType'] = $standardModel->getSubType($value['subType']);
            $list[$key]['distance'] = 999999;
            if(!empty($value['electronic_scenic_latlng']) && !empty($geohash)){
                $product_scenic_latlng = json_decode($value['electronic_scenic_latlng'],true);
                $distance = (new Poi())->getDistance($req_lat,$req_lng,$product_scenic_latlng['lat'],$product_scenic_latlng['lng']);
                $list[$key]['distance'] = sprintf('%.2f',$distance);
            }
            //获取关联的商品信息
            $list[$key]['goodsInfo'] = [];
            $list[$key]['showImg'] = "";
            if(!empty($value['goods_id'])){
                $list[$key]['goodsInfo'] = $standardModel->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                $image = $list[$key]['goodsInfo']['small_image']??[];
                $list[$key]['showImg'] = $standardModel->checkImgUrl($image[0]??"")??"";
//                $list[$key]['showImg'] = (new SD())->batchOssImgUrl($list[$key]['showImg']);
                $list[$key]['goodsprice'] = floatval($list[$key]['goodsInfo']['goodsprice'])??0;
                $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                unset($list[$key]['goodsInfo']['small_image']);
                $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
                $list[$key]['tags'] = !empty($list[$key]['goodsInfo']['tags'])?
                    array_merge($list[$key]['classificationTags'],$list[$key]['goodsInfo']['tags']):
                    $list[$key]['classificationTags'];
            }
        }
        var_dump('数据扩充：',microtime(true) - $start_time);

        $result['pageInfo'] = [
            'totalNum'=>$total,
            'totalPage'=>ceil($total/$offset),
            'page'=>(int)$page,
            'offset'=>(int)$offset,
            'list'=>$list
        ];
        //返回json 数据
        return $this->result('success',$result,200,'json');
    }

    public function geohashTest($lat,$lng)
    {
        return GeoHash::encode($lng,$lat);
    }
    //聚合搜索
    public function filterVirtualStandardAndGuideListByKeywords()
    {
        $post = request()->post();
        //鉴权
        $auth_res = $this->checAuth($post);
        if(is_array($auth_res)){
            return json_encode($auth_res);
        }elseif(!$auth_res){
            return json_encode(['code'=>400,'msg'=>'鉴权失败']);
        }

        $standardIds = $post['standardIds']??[];
        $guideIds = $post['guideIds']??[];
        $latLng = $post['latLng']??'';//基于经纬度进行hash
        if(empty($standardIds) && empty($guideIds)) return json_encode(['code'=>400,'msg'=>'缺少IDs']);
        $list = $guideList = [];
        $standardLimit = 10;
        $guideLimit = 5;
        if(!empty($standardIds)){
            $where['s.id'] = ['in',$standardIds];//选品IDS
            //增加筛选条件
            $keyword = !empty($post['keywords'])?trim($post['keywords']):'';
            $supplier_id = $post['supplierId']??'';
            //关键词搜索
            if(!empty($keyword)) $where['s.id|s.name|g.goods_tcode'] = ['like','%'.$keyword.'%'];

            //特定供应商的产品
            if(!empty($supplier_id)){
                //获取管理员ID
                $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
                if(!empty($supplier_admin_ids)){
                    $where['s.supplier_admin_id'] = ['in',$supplier_admin_ids];
                }
            }
            if(!empty($latLng)){
                list($req_lat,$req_lng) = explode(',',$latLng);
                if(!empty($req_lat) && !empty($req_lng)){
                    $geohash = GeoHash::encode($req_lng,$req_lat);
//                if(!empty($geohash)) $where['pe.electronic_scenic_geohash'] = ['like',substr($geohash,0,3).'%'];
                }
            }

            //按照参数的ids 进行排序
            $standardModel = new SD();
            $from = 'orderSystem';
            $where['s.status'] = 1;//启用的标品
            $where['s.is_deleted'] = 0;//未删除的标品

            //只针对虚拟产品 20200317 针对所有产品
            //$where['g.orderType'] = 'VirtualProduct';
            $standard_order_str = new Expression('field(s.id,'.implode(',',$standardIds).')');
            $list = db("standard s")
                ->join("goods g",'g.goods_id=s.goods_id','left')
                ->join("standardtrip st",'st.sid=s.id','left')
                ->join("city c",'c.id=st.startCityId','left')
                ->join("product_electronic pe",'pe.electronic_pro_id=st.trip_id','left')
                ->join("supplier_admin admin",'admin.supplier_admin_id=s.supplier_admin_id','left')
                ->field('s.id as standardId,s.name as standardName,s.type as standardType,introduce as subTitle,showImg,
            g.goods_id,g.goods_name,g.orderType,is_recommend,trip_id,
            startCityId,c.name as startCityName,c.kbx_id as kbxStartCityId,
            days,endDays,subType,toursLineTitle,specialInfo,topCate,admin.company_id as supplierId,
            pe.electronic_scenic_latlng')
                ->where($where)
                ->order($standard_order_str)
                ->limit($standardLimit)
                ->select();

            foreach ($list as $key=>$value){
                $list[$key]['id'] = $value['standardId'];
                $list[$key]['goods_name'] = $value['standardName'];
                $list[$key]['standardTypeName'] = $standardModel->getTypeName($value['standardType']);
                $list[$key]['classificationTags'] = $standardModel->getStandardTags($value['standardId']);
                $list[$key]['subType'] = $standardModel->getSubType($value['subType']);
                $list[$key]['distance'] = 999999;
                if(!empty($value['electronic_scenic_latlng']) && !empty($geohash)){
                    $product_scenic_latlng = json_decode($value['electronic_scenic_latlng'],true);
                    $distance = (new Poi())->getDistance($req_lat,$req_lng,$product_scenic_latlng['lat'],$product_scenic_latlng['lng']);
                    $list[$key]['distance'] = sprintf('%.2f',$distance);
                }
                //获取关联的商品信息
                $list[$key]['goodsInfo'] = [];
                $list[$key]['showImg'] = "";
                if(!empty($value['goods_id'])){
                    $list[$key]['goodsInfo'] = $standardModel->getLinkGoodsInfo($value['goods_id'],$value['standardId'],$from);
                    $image = $list[$key]['goodsInfo']['small_image']??[];
                    $list[$key]['showImg'] = $standardModel->checkImgUrl($image[0]??"")??"";
//                $list[$key]['showImg'] = (new SD())->batchOssImgUrl($list[$key]['showImg']);
                    $list[$key]['goodsprice'] = floatval($list[$key]['goodsInfo']['goodsprice'])??0;
                    $list[$key]['salesVolume'] = $list[$key]['goodsInfo']['goodssales']??"0";
                    unset($list[$key]['goodsInfo']['small_image']);
                    $list[$key]['startCityId'] = $value['startCityId']?:$list[$key]['goodsInfo']['city_id'];
                    $list[$key]['startCityName'] = $value['startCityName']?:$list[$key]['goodsInfo']['cityName'];
                    $list[$key]['kbxStartCityId'] = $value['kbxStartCityId']?:$list[$key]['goodsInfo']['kbxCityId'];
                    $list[$key]['tags'] = !empty($list[$key]['goodsInfo']['tags'])?
                        array_merge($list[$key]['classificationTags'],$list[$key]['goodsInfo']['tags']):
                        $list[$key]['classificationTags'];
                }
            }
        }
        if(!empty($guideIds)){
            //关键词搜索
            $where = [];//还原搜索条件
            $where['id'] = ['in',$guideIds];
            if(!empty($keyword)) $where['id|title|description'] = ['like','%'.$post['keywords'].'%'];
            //特定供应商的产品
            if(!empty($supplier_id)){
                //获取管理员ID
                $supplier_admin_ids = $this->getSupplierAdminIds($supplier_id);
                if(!empty($supplier_admin_ids)){
                    $where['supplier_admin_id'] = ['in',$supplier_admin_ids];
                }
            }
            $where['is_delete'] = 0;
            //按照参数的ids 进行排序
            $guide_order_str = new Expression('field(id,'.implode(',',$guideIds).')');
            $guideList = (new SD())->listGuide($where,1,$guideLimit,$guide_order_str);
            $guideList = $guideList['list'] ?? [];
        }

        $result['standardList'] = $list;
        $result['guideList'] = $guideList;
        //返回json 数据
        return $this->result('success',$result,200,'json');
    }
}